package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.enums.RedisCachePrefixEnum;
import com.lcf.framework.exception.SysException;
import com.lcf.framework.utils.RedisCacheUtils;
import com.lcf.framework.utils.UserUtils;
import com.lcf.framework.vo.PageVO;
import com.lcf.system.dao.SysTenantDao;
import com.lcf.system.dto.tenant.SysTenantDTO;
import com.lcf.system.dto.tenant.SysTenantEditDTO;
import com.lcf.system.entity.*;
import com.lcf.system.enums.SysRoleEnum;
import com.lcf.system.manager.SysTenantManager;
import com.lcf.system.manager.SysUserManager;
import com.lcf.system.query.tenant.SysTenantPageQuery;
import com.lcf.system.service.SysTenantService;
import com.lcf.system.vo.tenant.SysTenantVO;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 租户(SysTenant)表服务实现类
 *
 * @author lcf
 * @since 2025-03-02 23:00:13
 */
@Service("sysTenantService")
public class SysTenantServiceImpl extends ServiceImpl<SysTenantDao, SysTenant> implements SysTenantService {
    @Resource
    private RedisCacheUtils redisCacheUtils;
    @Resource
    private SysUserManager sysUserManager;
    @Resource
    private SysTenantManager sysTenantManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysTenantDTO dto) {
        sysTenantManager.checkExist(null, dto.getTenantName());

        SysTenant sysTenant = BeanUtil.copyProperties(dto, SysTenant.class);
        sysTenant.insert();

        long tenantId = sysTenant.getId();

        //添加租户管理员用户
        SysUser sysUser = new SysUser(dto.getUsername(), dto.getPassword(), dto.getTenantName());
        sysUserManager.checkExist(null, sysUser);

        sysUser.setPassword(UserUtils.passwordEncrypt(dto.getPassword()));
        sysUser.insert();

        long userId = sysUser.getId();
        //用户加入租户
        new SysTenantUser(tenantId, userId).insert();
        //添加管理员角色
        SysRole sysRole = new SysRole(SysRoleEnum.ADMIN);
        sysRole.setTenantId(tenantId);
        sysRole.insert();

        //绑定租户管理员角色
        SysUserRole sysUserRole = new SysUserRole(userId, sysRole.getId());
        sysUserRole.setTenantId(tenantId);
        sysUserRole.insert();
    }

    @Override
    public void edit(SysTenantEditDTO dto) {
        sysTenantManager.checkExist(UserUtils.getTenantId(), dto.getTenantName());

        SysTenant sysTenant = BeanUtil.copyProperties(dto, SysTenant.class);
        sysTenant.setId(UserUtils.getTenantId());
        sysTenant.updateById();
    }

    @Override
    public void bindEmail(String code) {
        String key = RedisCachePrefixEnum.EMAIL_BIND_CODE.getKey(code);
        String email = redisCacheUtils.get(key);
        if (StringUtils.isBlank(email)) {
            throw new SysException("验证码错误或已过期");
        }

        Db.lambdaUpdate(SysTenant.class)
                .eq(SysTenant::getId, UserUtils.getTenantId())
                .set(SysTenant::getContactEmail, email)
                .update();

        redisCacheUtils.del(key);
    }

    @Override
    public void bindMobile(String code) {
        String key = RedisCachePrefixEnum.PHONE_BIND_CODE.getKey(code);
        String phone = redisCacheUtils.get(key);
        if (StringUtils.isBlank(phone)) {
            throw new SysException("验证码错误或已过期");
        }

        Db.lambdaUpdate(SysTenant.class)
                .eq(SysTenant::getId, UserUtils.getTenantId())
                .set(SysTenant::getContactPhone, phone)
                .update();

        redisCacheUtils.del(key);
    }


    @Override
    public PageVO<SysTenantVO> page(SysTenantPageQuery query) {
        Page<SysTenant> page = Db.lambdaQuery(SysTenant.class)
                .like(StringUtils.isNotBlank(query.getTenantName()), SysTenant::getTenantName, query.getTenantName())
                .eq(StringUtils.isNotBlank(query.getContactPerson()), SysTenant::getContactPerson, query.getContactPerson())
                .eq(StringUtils.isNotBlank(query.getContactPhone()), SysTenant::getContactPhone, query.getContactPhone())
                .page(query.toPage());

        return new PageVO<>(page, SysTenantVO.class);
    }

    @Override
    public SysTenantVO detail(long tenantId) {
        SysTenant one = Db.lambdaQuery(SysTenant.class).eq(SysTenant::getId, tenantId).one();
        if (one == null) {
            throw new RuntimeException("租户不存在");
        }

        return BeanUtil.copyProperties(one, SysTenantVO.class);
    }
}

